#!/usr/bin/perl

use Module::Build;

my $class = Module::Build->subclass(
	class => 'My::Builder',
	code => << 'EOC'

use strict;

sub check_prereq {
	my $self = shift;

	my $gtk_ok = 0;
	eval 'use Gtk2';
	if ($@) {
		warn " * ERROR: Could not load perl module Gtk2\n";
	}
	elsif (! Gtk2->CHECK_VERSION(2, 4, 0)) {
		my $version = join '.', Gtk2->GET_VERSION_INFO;
		warn " * ERROR: gtk+ version $version is installed, but we need >=2.4.0\n" .
		     "   If you think you have the right version of gtk+ installed, try recompiling the Gtk2 perl package.\n";
	}
	else { 
		#my $version = join '.', Gtk2->GET_VERSION_INFO;
		#warn "# gtk version $version found\n";
		$gtk_ok = 1;
	}

	my $prereq_ok = $self->SUPER::check_prereq(@_);
	
	warn "ERRORS FOUND IN PREREQUISITES.\n"
		if $prereq_ok && ! $gtk_ok;
	
	return $prereq_ok && $gtk_ok;
}

sub ACTION_build {
	# copy share data and call parent
	my $self = shift;
	$self->{properties}{script_files} = ['bin/zim']; # Bug in M:B ?

	$self->do_system($self->perl, './Config.PL');

	my $blib = $self->blib;
	for (@{$self->rscan_dir('share')}) {
		next if /^\.|[\/\\]\./ or -d $_;
		my $to = $_;
		$to =~ s/_zim\.config$/.zim.config/;
		$self->copy_if_modified(
			from => $_,
			to   => File::Spec->catfile($blib, $to) );
	}
	$self->copy_if_modified(
		from => 'Changes',
		to   => File::Spec->catfile($blib, qw/share zim doc zim changelog.txt/ ) );
	
	$self->SUPER::ACTION_build(@_)
}

sub install_types { # Why O Why is this necessary ?
	my $self = shift;
	return 'share', $self->SUPER::install_types(@_);
}

sub ACTION_install {
	# define install path for share data and call parent
	my $self = shift;
	my $p = $self->{properties};
	unless (
		exists $p->{install_path}{share}
		or $p->{install_base}
	) {
		my $bindir = $self->install_destination('script');
		my @dirs = File::Spec->splitdir($bindir);
		pop @dirs; # 'bin'
		my $sharedir = File::Spec->catdir(@dirs, 'share');
		$p->{install_path}{share} = $sharedir;
	}

	$self->SUPER::ACTION_install(@_);

	print "Trying to run 'update-desktop-database' ... ";
	print system('update-desktop-database') ? "Failed\n" : "Ok\n";
}

sub install_base_relative { # define install base path for share data
	my ($self, $type) = @_;
	return 'share' if $type eq 'share';
	return 'bin' if $type eq 'script';
	$self->SUPER::install_base_relative($type);
}

sub ACTION_test {
	my $self = shift;
	$self->do_system($self->perl, './TRepository.PL');
	$self->SUPER::ACTION_test(@_)
}

=head1 ACTIONS

=over 4

=item C<static>

Builds a self-contained excutable for zim. Needs the L<PAR> and
L<ExtUtils::PkgConfig> modules.

=back

=cut

sub ACTION_static {
	my $self = shift;
	warn "## WARNING: Static building is experimental - feedback is welcome\n";
	warn "## You need to have zim installed before running this command\n";
	warn "## You can pass extra options to 'pp' using PP_OPTS\n";
	eval 'use ExtUtils::PkgConfig';
	die $@ if $@;
	sleep 5;
	$self->ACTION_build;
	my @libs = map {s/^-l//i; ('-l', $_)} grep {length $_} split /\s+/,
		ExtUtils::PkgConfig->libs('gtk+-2.0');
	my @add = ('-a', 'share');
	open MANIFEST, '<MANIFEST' or die "Could not read MANIFEST";
	my @modules;
	for (<MANIFEST>) { # grep modules from the manifest
		/^lib\/(\S+?)\.pm/ or next;
		my $mod = $1;
		$mod =~ s/\//::/g;
		push @modules, '-M', $mod;
	}
	close MANIFEST;
	my $script = File::Spec->catfile(qw/script zim/);
	my $blib = File::Spec->catdir($ENV{PWD}, $self->blib);
	my $libdir = File::Spec->catdir($blib, 'lib');
	print ">> cd $blib\n";
	chdir $blib or die "Could not open dir $blib\n";
	$ENV{PWD} = $blib;
	print ">> pp -I $libdir -o zim @libs @add @modules $script\n";
	system qw{pp -o ../zim}, @libs, @add, @modules, $script;
	warn "\n## Your executable is ready\n";
}
EOC
);
    
my $build = $class->new(
	dist_name => 'Zim',
	dist_version_from => 'lib/Zim.pm',
	dist_abstract => 'A desktop wiki',
	dist_author => 'Jaap Karssenberg <pardus@cpan.org>',
	license => 'perl',
	script_files => ['bin/zim'],
	requires => {
		'perl'           => '5.8.0',
		'Gtk2'           => '1.040',
		# Older doesn't support Gtk2::UIManager I think
		'POSIX'          => 0,
		'IO::File'       => 0,
		'File::Spec'     => 0,
		'File::Copy'     => 0,
		'File::BaseDir'  => 0,
		'File::MimeInfo' => '0.12',
		'File::DesktopEntry' => 0,
		'Encode'         => 0,
		($^O eq 'MSWin32' ? (
			'Win32::Process'   => 0,
		) : ()),
	},
	recommends => {
		'Gtk2::TrayIcon' => 0,
		'Gtk2::Spell'    => 0,
#		'File::DesktopEntry' => 1.0,
	},
	build_requires => {
		'Module::Build'  => '0.24',
		'Test::More'     => 0,
	},
	create_makefile_pl => 'passthrough',
	#dynamic_config => 1,
);

$build->create_build_script;

